<template>
  <div class="app-container">
    <div class="head-container">
      <el-dialog
        v-if="editOfficeVisible"
        fullscreen
        class="onlyOffice"
        :visible.sync="editOfficeVisible"
        close-on-press-escape
        :before-close="closeEditor">
        <officeEdit ref="onlineEditRef" :option="option"></officeEdit>
      </el-dialog>
      <div style="margin-bottom: 5px">
        <el-input class="input" size="small" style="width:200px" v-model="listQuery.condition" placeholder="请输入文件名称"
                  clearable></el-input>
        <el-button
          type="success"
          icon="el-icon-search"
          size="mini"
          @click="getTablePage(true)"
        >
          查询
        </el-button>
        <el-button
          style="margin-left: 10px"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="openDialogTableForm(false)"
        >上传
        </el-button>
      </div>
      <el-table
        ref="genTable"
        v-loading="listLoading"
        :data="list"
        border
        fit
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column type="index" width="50" label="序号">
          <template slot-scope="scope">
            <span>{{listQuery.pageNo * listQuery.pageSize +scope.row.listIndex + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="文件名" min-width="120"/>
        <el-table-column prop="ext" label="文件后缀" min-width="30"/>
        <el-table-column prop="filePath" label="文件路径" min-width="120"/>
        <el-table-column prop="module" label="文件所属模块" min-width="50"/>
        <el-table-column prop="part" label="文件所属区域" min-width="50"/>
        <el-table-column align="left" label="操作" width="460">
          <template slot-scope="scope">
            <el-button style="margin-left: 10px" type="danger" size="mini" @click="preview(scope.row)">预览</el-button>
            <el-button style="margin-left: 10px" type="danger" size="mini" @click="download(scope.row)">下载</el-button>
            <el-button style="margin-left: 10px" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            <el-button style="margin-left: 10px" type="primary" v-show="scope.row.isDoc" size="mini"
                       @click="openOnlineEdit(scope.row)">在线编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        style="margin-top: 8px;"
        layout="total, prev, pager, next"
        :page-size="listQuery.pageSize"
        :total="total"
        prev-text="上一页"
        next-text="下一页"
        :current-page="listQuery.pageNo+1"
        @current-change="paginationChange"
      >
      </el-pagination>
      <!-- 弹出框新增table -->
      <el-dialog title="文件上传demo" :visible.sync="dialogVisible" width="800px">
        <el-form
          ref="tableForm"
          :model="tableForm"
          label-position="right"
          label-width="120px"
          style="width: 600px; margin-left:20px; margin-right: 0px;"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="文件：" required>
                <uploader
                  v-if="dialogVisible"
                  ref="file"
                  :detail-id="tableForm.id"
                  :fileSystem="fileSystem"
                  :detail-type="doType"
                  :disabled="doType == 'view'"
                  type="mul"
                  @change="changeFile"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属模块：" required>
                <el-input v-model="tableForm.module" maxlength="60"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" align="center">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveTable">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>

  import {editTable, deleteFile, preview, download, getTablePage} from '@/api/file'
  import msgUtil from '@/utils/msgUtil'
  import {Base64} from 'js-base64'
  import officeEdit from './onlineEdit'
  import {handleDocType} from '@/utils/onlyofficeUtil'
  import uploader from "@/components/Upload/uploadFile"

  const officePath = process.env.VUE_APP_ONLY_OFFICE
  const basePath = process.env.VUE_APP_BASE_API
  export default {
    components: {
      officeEdit,
      uploader
    },
    data() {
      return {
        editOfficeVisible: false,
        isEdit: false,
        // 上传文件所在的表单, 业务主表的表单
        tableForm: {
          id: '',
          module: '',
          name: ''
        },
        dialogVisible: false, // 弹出的新增修改表单窗口
        selTableId: 0, // 选中行的tableId
        selectedIds: [],
        selType: 0, // 选中的创建文件类型
        tableKey: 0,
        list: null,
        listLoading: false,
        total: 0,
        option: {
          url: '',
          isEdit: true,
          fileType: '',
          title: '',
          token: 'token',
          user: {
            id: '',
            name: ''
          },
          mode: 'edit',
          editUrl: '',
          key: ''
        },
        listQuery: {
          pageNo: 0,
          pageSize: 10,
          condition: '',
        },
        // 定位文件属于哪个模块
        fileSystem:{
          sys: "demo",
          module: "file",
          part: "one",
        },
        // 表单操作类型， edit, view
        doType:'',
      }
    },
    created() {
      this.getTablePage()
    },
    methods: {
      closeEditor(done) {
        done()
        this.$refs.onlineEditRef.docEditor.destroyEditor()
      },
      openOnlineEdit(row) {
        preview(row.id).then(res => {
          let sysUser = JSON.parse(localStorage.getItem('sysUser'))
          this.option.user.id = sysUser.id
          this.option.user.name = sysUser.name
          this.option.url = res.data
          const baseUrl = process.env.VUE_APP_BASE_API === '/' ? '' : process.env.VUE_APP_BASE_API
          this.option.editUrl = baseUrl + `/file-server/onlyoffice/editCallBack?userId=${sysUser.id}&fileId=${row.id}`
          this.option.basePath = `${officePath}/web-apps/apps/`,
            this.option.title = row.name
          this.option.fileType = row.ext
          this.editOfficeVisible = true
        })

      },
      // 保存数据表配置
      saveTable() {
        this.$refs.tableForm.validate(valid => {
          if (valid) {
            this.$refs.file.saveAll('testEmptyForm');
            this.dialogVisible = false
            this.getTablePage()
            msgUtil.success2('数据上传成功')
            // 修改
            // editTable(this.tableForm).then(res => {
            //   let id = res.data
            //   // 重点： 表单保存后要调用saveAll方法保存文件
            //   this.$refs.file.saveAll(id);
            //   this.dialogVisible = false
            //   msgUtil.success2('数据表修改成功')
            //   this.getTablePage()
            // })
          }
        })
      },
      // 删除
      handleDelete(row) {
        msgUtil.confirm('确认删除表数据?').then(async () => {
          await deleteFile(row.id)
          msgUtil.success2('删除成功!')
          this.getTablePage()
        })
      },
      getTablePage(reload) {
        if (reload) {
          this.listQuery.pageNo = 0
        }
        this.listLoading = true
        getTablePage(this.listQuery).then(res => {
          this.list = res.data.content
          this.total = res.data.totalElements
          this.listLoading = false
          res.data.content.forEach((item, index) => {
            item.isDoc = handleDocType(item.ext) !== ''
            item.listIndex = index
          });
          this.$nextTick(() => {
            this.listLoading = false
          })
        })
      },
      preview(row) {
        preview(row.id).then(response => {
          window.open(basePath+'/onlinePreview?url='+encodeURIComponent(Base64.encode(response.data)));
        })
      },
      download(row) {
        download(row.id).then(res => {
          var blob = new Blob([res]);
          var downloadElement = document.createElement('a');
          var href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.style.display = 'none';
          downloadElement.href = href;
          downloadElement.download = decodeURI(row.name); //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        }).catch(res => {
          msgUtil.error2('下载失败!')
        })
      },
      paginationChange(index) {
        this.listQuery.pageNo = index - 1
        this.getTablePage()
      },
      handleSelectionChange(val) {
        if (val.length < this.selectedIds.length) {
          this.selectedIds = []
          val.forEach(row => {
            this.selectedIds.push(row.id)
          })
        } else {
          val.forEach(row => {
            if (!this.selectedIds.includes(row.id)) {
              this.selectedIds.push(row.id)
            }
          })
        }
      },
      openDialogTableForm(isEdit, row) {
        this.isEdit = isEdit
        if (isEdit) {
          this.tableForm = row
        } else {
          this.tableForm = {
            id: '',
            module: '',
          }
        }
        this.dialogVisible = true
      },
      changeFile(oldFiles, newFiles) {
        let len = newFiles.length
        if (!newFiles || !len) {
          return
        }
        let f = newFiles[len-1]
        this.tableForm.name = f.name
      }
    }
  }
</script>
<style>
  .onlyOffice .el-dialog__body {
    height: 100%;
  }
</style>
